# -*- coding: utf-8 -*-

from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect, HttpResponse, Http404, HttpResponseForbidden
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from django.conf import settings
from django import newforms as forms
from django.newforms import form_for_instance, form_for_model, save_instance, form_for_fields
from django.core.paginator import ObjectPaginator, InvalidPage

from articles.models import Article

import re, string

#------------------------------------------------------------------------------ 
def slugify(string):
    string = re.sub('\s+', '_', string)
    string = re.sub('[^\w.-]', '', string)
    return string.strip('_.- ').lower()

#------------------------------------------------------------------------------ 
def articles_list(request):
    "Articles list"
    num_per_page = 10 #number of recipes per page
    page = 1          #default page number
    
    page = int(request.GET.get('page','1'))
    
    items = Article.objects.all().order_by('-date_added')
    
    # paginate it
    paginator = ObjectPaginator(items, num_per_page)
    try:
        items = paginator.get_page(page-1)
    except InvalidPage:
        page = 1
        items = paginator.get_page(page-1)
    
    content = {
               "items": items,
               "paginator": paginator,
               "current_page": page,
               "pages": range(1, paginator.pages+1),
               }
    
    return render_to_response("articles_list.html", content, context_instance=RequestContext(request))

#------------------------------------------------------------------------------ 
def article(request, item_id):
    "Article"
    
    item = Article.objects.get(pk=item_id)
    
    content = {
               "item": item,
               }
    
    return render_to_response("article.html", content, context_instance=RequestContext(request))

#------------------------------------------------------------------------------
@login_required 
def article_delete(request, item_id):
    "Article delete"
    
    if not request.user.is_staff:
        return HttpResponseForbidden
    
    item = Article.objects.get(pk=item_id)
    item.delete()
    
    return HttpResponseRedirect('/blog/')

#------------------------------------------------------------------------------ 
@login_required
def article_add(request):
    "Add new article"
    
    ItemForm = form_for_model(Article)
    
    if request.method == "POST":
        item_form = ItemForm(request.POST)
    
        if item_form.is_valid():
            item = item_form.save(False)
            item.id = slugify(item.title)
            item.user = request.user
            item.save()
            return HttpResponseRedirect("/blog/%s/" % item.id)
    else:
        item_form = ItemForm()
    
    return render_to_response("article_edit.html", {'form' : item_form}, context_instance=RequestContext(request))

#------------------------------------------------------------------------------ 
@login_required
def article_edit(request, item_id):
    "Edit article"
    item = Article.objects.get(pk=item_id)
    
    if (request.user != item.user) and (not request.user.is_staff):
        return HttpResponseForbidden
    
    ItemForm = form_for_instance(item)
    
    if request.method == "POST":
        item_form = ItemForm(request.POST)
    
        if item_form.is_valid():
            save_instance(item_form, item, commit=True)
            return HttpResponseRedirect("/blog/%s/" % item_id)
    else:
        item_form = ItemForm()
    
    return render_to_response("article_edit.html", {'form' : item_form}, context_instance=RequestContext(request))

#------------------------------------------------------------------------------ 
